package com.ctrip.ibu.permissions.security.util;

import cn.hutool.json.JSONObject;
import com.ctrip.ibu.permissions.common.exception.BaseException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * description
 *
 * @author r.shi 2020/02/27 14:15
 */
public class SecurityUtils {

    public static UserDetails getUserDetails() {
        UserDetails userDetails;
        try {
            userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        } catch (Exception e) {
            throw new BaseException( "登录状态过期", HttpStatus.UNAUTHORIZED);
        }
        return userDetails;
    }

    public static String getUsername(){
        Object obj = getUserDetails();
        return new JSONObject(obj).get("username", String.class);
    }
}
